<template>
  <div>
    <div style="display: flex; align-items: center; margin-bottom: 10px;">
      <el-input
        v-model="lotId"
        placeholder="请输入 LotId"
        style="width: 300px; margin-right: 10px"
      />
      <el-button type="primary" @click="startProcess">开始处理 CSV</el-button>
      <!--<el-button type="info" @click="testBackendGet" style="margin-left: 10px">测试 GET 接口</el-button>-->
    </div>
    <div style="display: flex; align-items: center;">
      <el-input
        v-model="outputBaseDirectory"
        placeholder="请输入需要压缩的目录"
        style="width: 300px; margin-right: 10px;"
      />
      <el-button type="success" @click="zipCsvFiles">压缩 CSV 文件</el-button>
    </div>

    <div style="display: flex; align-items: center; margin-top: 10px;">
      <el-input
        v-model="folderPath"
        placeholder="请输入需要GZip压缩的文件夹路径"
        style="width: 300px; margin-right: 10px;"
      />
      <el-button type="primary" @click="gZipStdFiles">GZip 压缩 STD/STDF 文件</el-button>
    </div>

    <div
      style="
        position: absolute;
        top: 30px;
        right: 30px;
        width: 220px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,.04);
        background: #fff;
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: stretch;
      "
    >
      <div style="font-weight: bold; margin-bottom: 18px; text-align: center; color: #409EFF;">
        CSV To MAP
      </div>
      <el-upload
        class="upload-demo"
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="false"
        ref="uploadRef"
        style="display: flex; flex-direction: column; align-items: stretch;"
      >
        <el-button
          type="success"
          style="width: 100%;"
        >
          选择 CSV 文件
        </el-button>
      </el-upload>
    </div>

    <div class="console-output">
      <pre id="console"></pre>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios"
import { ElLoading } from 'element-plus'; // 引入 ElLoading

defineOptions({
  name: "CsvProcessor"
});

const lotId = ref("");
const output = ref("");
const outputBaseDirectory = ref(""); // 新增输出目录引用
const folderPath = ref(""); // 新增文件夹路径引用
const selectedFile = ref(null); // 新增文件选择引用
const uploadRef = ref(null); // 上传组件引用

// 后端接口地址（按你的服务器IP配置）
//const API_BASE_URL = "http://localhost:5058"; 
const API_BASE_URL = "http://10.0.8.42:8090"; 
const API_URL = `${API_BASE_URL}/CsvProcess/process`;
const API_TEST_GET_URL = `${API_BASE_URL}/CsvProcess/test`; // 新增 GET 测试接口地址
const API_ZIP_URL = `${API_BASE_URL}/CsvProcess/ZipCsvFiles`; // 新增压缩接口地址
const API_GZIP_URL = `${API_BASE_URL}/CsvProcess/GZipStdFiles`; // 新增 GZip 接口地址
const API_CSV_TO_MAP_URL = `${API_BASE_URL}/CsvProcess/CsvToMap`; // 新增 CSV To MAP 接口地址

async function startProcess() {
  if (!lotId.value.trim()) {
    ElMessage.warning("请输入 LotId");
    return;
  }

  output.value = "正在请求后端处理，请稍候...\n";
  document.getElementById("console").textContent = output.value;
console.log(API_URL)

  const loadingInstance = ElLoading.service({ // 显示加载动画
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const response = await axios.post(API_URL, {
        LotId: lotId.value
    });

    // axios 会直接将数据放在 response.data 中，无需流式读取
    document.getElementById("console").textContent = String(response.data);

    if (response.status !== 200) { // 检查状态码是否为 200
      ElMessage.error("处理失败：" + (response.data || response.statusText || response.status));
    } else {
      ElMessage.success("处理完成！");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("请求失败：" + (err.response && err.response.data ? err.response.data : err.message));
  } finally {
    loadingInstance.close(); // 关闭加载动画
  }
}

// 新增 GET 测试方法
async function testBackendGet() {
  output.value = "正在请求后端 GET 测试接口，请稍候...\n";
  document.getElementById("console").textContent = output.value;
  try {
    const response = await axios.get(API_TEST_GET_URL);
    if (response.status !== 200) { // 修改这里，检查 status 而不是 ok
      ElMessage.error("GET 测试失败：" + (response.statusText || response.status));
    } else {
      document.getElementById("console").textContent = String(response.data);
      ElMessage.success("GET 测试完成！");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("GET 测试请求失败，无法连接服务器");
  }
}

async function zipCsvFiles() {
  if (!outputBaseDirectory.value.trim()) {
    ElMessage.warning("请输入需要压缩的目录");
    return;
  }

  output.value = "正在请求后端压缩文件，请稍候...\n";
  document.getElementById("console").textContent = output.value;

  const loadingInstance = ElLoading.service({
    text: '压缩中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const response = await axios.post(API_ZIP_URL, null, { // null for body, query param for outputBaseDirectory
      params: {
        outputBaseDirectory: outputBaseDirectory.value
      }
    });

    document.getElementById("console").textContent = String(response.data);

    if (response.status !== 200) {
      ElMessage.error("压缩失败：" + (response.data || response.statusText || response.status));
    } else {
      ElMessage.success("压缩完成！");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("请求失败：" + (err.response && err.response.data ? err.response.data : err.message));
  } finally {
    loadingInstance.close();
  }
}

async function gZipStdFiles() {
  if (!folderPath.value.trim()) {
    ElMessage.warning("请输入需要GZip压缩的文件夹路径");
    return;
  }

  output.value = "正在请求后端进行 GZip 压缩，请稍候...\n";
  document.getElementById("console").textContent = output.value;

  const loadingInstance = ElLoading.service({
    text: 'GZip 压缩中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const response = await axios.post(API_GZIP_URL, null, {
      params: {
        folderPath: folderPath.value
      }
    });

    document.getElementById("console").textContent = String(response.data);

    if (response.status !== 200) {
      ElMessage.error("GZip 压缩失败：" + (response.data || response.statusText || response.status));
    } else {
      ElMessage.success("GZip 压缩完成！");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("请求失败：" + (err.response && err.response.data ? err.response.data : err.message));
  } finally {
    loadingInstance.close();
  }
}

// 处理文件选择
const handleFileChange = async (file) => {
  selectedFile.value = file.raw;
  ElMessage.success(`已选择文件: ${file.name}`);
  // 文件选择后立即触发上传和处理
  await uploadCsvAndDownloadMap();
};

// CSV To MAP 上传和下载
async function uploadCsvAndDownloadMap() {
  if (!selectedFile.value) {
    ElMessage.warning("请先选择一个 CSV 文件");
    return;
  }

  output.value = "正在上传 CSV 文件并处理，请稍候...\n";
  document.getElementById("console").textContent = output.value;

  const loadingInstance = ElLoading.service({
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const formData = new FormData();
    formData.append("file", selectedFile.value);

    const response = await axios.post(API_CSV_TO_MAP_URL, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      responseType: 'blob', // 明确指出响应类型为 blob
    });

    if (response.status === 200) {
      const blob = new Blob([response.data], { type: response.headers['content-type'] });
      const contentDisposition = response.headers['content-disposition'];
      console.log('前端接收到的 Content-Disposition:', contentDisposition); // 添加这行
      let fileName = "output.in";
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename\*?=(?:utf-8\'\')?([^;]+)/i);
        if (fileNameMatch && fileNameMatch[1]) {
          try {
            fileName = decodeURIComponent(fileNameMatch[1]);
          } catch (e) {
            console.error('Failed to decode file name:', e);
            fileName = fileNameMatch[1]; // 如果解码失败，则使用原始捕获的字符串
          }
        }
      }

    

      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      ElMessage.success("CSV To MAP 处理完成，文件已下载！");
    } else {
      ElMessage.error("CSV To MAP 处理失败：" + (response.statusText || response.status));
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("请求失败：" + (err.response && err.response.data ? (await err.response.data.text()) : err.message));
  } finally {
    loadingInstance.close();
    selectedFile.value = null; // 清空已选择的文件
    uploadRef.value.clearFiles(); // 清空文件列表
  }
}
</script>

<style scoped>
.console-output {
  margin-top: 20px;
  background-color: #000;
  color: #0f0;
  font-family: monospace;
  padding: 10px;
  height: 70vh;
  overflow-y: scroll;
  border: 1px solid #333;
}
</style>
